#include"HttpServer.hpp"
#include"Err.hpp"
#include"Util.hpp"
#include<memory>
#include<vector>
const std::string SEP="\r\n";
//webserver不能直接将整站目录给用户,用户不能直接访问目录（stat判断）
//需要默认首页
const std::string defaultHomePage="index.html";
const std::string webRoot="./wwwroot";
class HttpRequest
{
    public:
    HttpRequest():path_(webRoot){}
    ~HttpRequest(){}
    void Print()
    {
        logMessage(Info,"method:%s,url:%s,version:%s",method_.c_str(),url_.c_str(),httpVersion_.c_str());
        for(const auto& line:body_)
        {
            logMessage(Debug,"-%S",line.c_str());
        }
        logMessage(Debug,"path:%S",path_.c_str());
    }
   
    std::string method_;
    std::string url_;
    std::string httpVersion_;
    std::vector<std::string> body_;
    std::string path_;
    std::string suffix_;


};
HttpRequest Deserialize(std::string& message)
{   
    HttpRequest req;
    //1.读到第一行
    std::string line=Util::ReadOneLine(message,SEP);
    //2.解析第一行
    Util::ParseRequestLine(line,&req.method_,&req.url_,&req.httpVersion_);
    
    while (!message.empty())
    {
        line=Util::ReadOneLine(message,SEP);
        req.body_.push_back(line);
    }
    //url:/a/b/c.html
    req.path_+=req.url_;
    //默认首页
    if(req.path_[req.path_.size()-1]=='/') req.path_+=defaultHomePage;
    //拿访问资源后缀
    auto pos=req.path_.rfind(".");
    if(pos==std::string::npos) req.suffix_=".html";
    else req.suffix_=req.path_.substr(pos);
    
    return req;
}
std::string GetContentType(const std::string& suffix)
{
    std::string content_type = "Content-Type: ";
    if (suffix == ".html" || suffix == ".htm")
        content_type + "text/html";
    else if (suffix == ".css")
        content_type += "text/css";
    else if (suffix == ".js")
        content_type += "application/x-javascript";
    else if (suffix == ".png")
        content_type += "image/png";
    else if (suffix == ".jpg")
        content_type += "image/jpeg";
    else
    {
    }
    return content_type + SEP;
}

std::string HandlerHttp(std::string& message)
{
    //1.读取请求 反序列化 分析请求
    HttpRequest req=Deserialize(message);
    req.Print();
    //2.使用请求
    std::string body;
    
    Util::ReadFile(req.path_,&body);
    std::string response="HTTP/1.0 200 OK"+SEP;
    response+="Content-Length: "+std::to_string(body.size())+SEP;

    //response+="Content-Type:  text/html"+SEP;
    response+=GetContentType(req.suffix_);
    response+=SEP;
    response+=body;

    return response;
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);
    std::unique_ptr<HttpServer> tsvr(new HttpServer(HandlerHttp, port)); // TODO
    tsvr->InitServer();
    tsvr->Start();

    return 0;
}